package com.svanberg.movielib.gui;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Collection;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JPanel;

import com.svanberg.movielib.Movie;
import com.svanberg.movielib.Movie.Genre;

public class GenreDialog extends JDialog
{
	private final Collection<Genre> genres;
	
	public GenreDialog(Collection<Genre> genres)
	{
		this(null, genres);
	}
	
	public GenreDialog(Window owner, final Collection<Genre> genres)
	{
		super(owner);
		this.genres = genres;
		
		int numGenres = Movie.Genre.values().length;
		int cols = (int)Math.sqrt(numGenres);
		int rows = (int)Math.ceil(numGenres / (float)cols);
		
		JPanel genreGrid = new JPanel(new GridLayout(rows, cols));
		for (final Genre genre : Genre.values())
		{
			JCheckBox box = new JCheckBox(genre.toString(), genres.contains(genre));
			box.addItemListener(new ItemListener()
			{
				public void itemStateChanged(ItemEvent e)
				{
					if (e.getStateChange() == ItemEvent.SELECTED) 
						genres.add(genre);
					else
						genres.remove(genre);
				}
			});
			genreGrid.add(box);
		}
		add(genreGrid, BorderLayout.CENTER);
		
		JPanel buttons = new JPanel();
		JButton ok = new JButton("OK");
		ok.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				dispose();
			}
		});
		buttons.add(ok);
		add(buttons, BorderLayout.SOUTH);
		
		getRootPane().setDefaultButton(ok);
		pack();
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setLocationRelativeTo(getOwner());
		setResizable(false);
	}
}
